import Compressor from 'compressorjs';

export const getToken = () => uni.getStorageSync('token') || '';

export const removeToken = () => uni.removeStorageSync('token');

export const base64Encode = (str) => {
    // 将字符串转换为 UTF-8 编码的字节数组
    const utf8Bytes = new TextEncoder().encode(str);
    // 将字节数组转换为 Base64 字符串
    return btoa(String.fromCharCode.apply(null, utf8Bytes));
};

export const base64Decode = (base64) => {
    // 将 Base64 字符串转换为字节数组
    const byteString = atob(base64);
    // 将字节数组转换为 UTF-8 字符串
    const bytes = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
        bytes[i] = byteString.charCodeAt(i);
    }
    return new TextDecoder().decode(bytes);
};

export const goPageByPath = (path, query = {}) => {
    if (!path) {
        throw new Error('缺少必须的path参数');
    }
    let queryLen = Object.keys(query).length;
    let queryStr = '';
    if (queryLen) {
        queryStr = Object.keys(query)
            .map((key) => `${key}=${query[key]}`)
            .join('&');
        queryStr = `?${queryStr}`;
    }
    uni.navigateTo({url: `${path}${queryStr}`});
};

// 表单重置
export function resetForm(refName) {
    if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
    }
}

// 判断 是否是数字
export const isStrictNumber = (value) => {
    return typeof value === 'number' && !isNaN(value);
};

// 获取文件的后缀名,不包含 .
export const getFileExt = (fileName) => {
    return fileName.split('.').pop();
};

// 临时路径转file对象 针对h5端
export const tempFilePathToFile = ({tempFilePath, fileName}) => {
    if (!tempFilePath) {
        return Promise.resolve(null);
    }
    return new Promise(async (resolve, reject) => {
        try {
            const response = await fetch(tempFilePath);
            const blob = await response.blob();
            const mimeType = response.headers.get('content-type');
            const file = new File([blob], fileName, {type: mimeType});
            resolve(file);
        } catch (error) {
            resolve(null);
        }
    });
};

// 压缩文件
export const compressFile = (file, options) => {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
            ...options,
            success(result) {
                resolve(result);
            },
            error(err) {
                reject(err);
            },
        });
    });
};
